package com.qfjy.service.Impl;


import com.alibaba.druid.util.StringUtils;
import com.qfjy.entity.MeetingPub;
import com.qfjy.entity.User;
import com.qfjy.mapper.MeetingGrabMapper;
import com.qfjy.mapper.MeetingPubMapper;
import com.qfjy.mapper.UserMapper;
import com.qfjy.service.MeetingGrabService;
import com.qfjy.service.MeetingPubService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class MeetingPubSeriveImpl implements MeetingPubService {
    @Autowired
    private MeetingPubMapper meetingPubMapper;

    @Autowired
    private UserMapper userMapper;

   @Autowired
    private MeetingGrabMapper meetingGrabMapper;

    /**
     *
     * @param meeting
     * @return
     */
    @Override
    public int insert(MeetingPub meeting) {
        meeting.setId(UUID.randomUUID().toString());
        meeting.setStatus(1);
        meeting.setPcode(this.pcodeGenner(meeting.getPtime()));
        meeting.setCreatedate(new Date());
        System.out.println(meeting);
        return meetingPubMapper.insert(meeting);
    }

    @Override
    public List<MeetingPub> selectMeetingPubList(String uid) {
        List<MeetingPub> meetingPubs = meetingPubMapper.selectMeetingPubList(uid);
        return meetingPubs;
    }

    @Override
    public List<MeetingPub> selectListMeetingGrabListByUid(String uid, String pid) {
        List<MeetingPub> meetingPubs = meetingPubMapper.selectListMeetingGrabListByUid(uid, pid);
        return meetingPubs;
    }

    /**
     * 查询抢单人信息
     * @param pid
     * @return
     */
    @Override
    public List<User> selectUserByPid(String pid) {
        return userMapper.selectUserByPid(pid);
    }
    @Transactional
    @Override
    public int chooseUserMeeting(String uid, String pid) {

        System.out.println("service层"+uid+"\t"+pid);
        int i = meetingGrabMapper.updataMeetingGrabChooseFail(pid);
        if (i==0) {
            log.info("发生异常事务回滚"+pid);
            throw new RuntimeException("修改改单用户匹配失败");
        }

        int i1 = meetingGrabMapper.updataMeetingGrabChooseSuccess(uid, pid);
        if(i1==0){
            log.info("发生异常事务回滚"+pid);
            throw new RuntimeException("修改改单用户匹配失败");
        }
        return 1;



    }

    /**
     * 会议编号生成原则
     * 会议召开日期
     */
        public String pcodeGenner(String ptime){
            String str=ptime.substring(0,10).replace("-","");
            String s = meetingPubMapper.selectMaxPcodeByPtime(str);
            System.out.println("pcode:"+s);
            if(StringUtils.isEmpty(s)){
                 return str+"001";
            }else{
                long num=Long.parseLong(s)+1;
                return ""+num;
            }

        }


}